﻿using AutoMapper;
using QYmall.Core.Common.Emum;
using QYmall.Core.Common.Extensions;
using QYmall.Core.Common.Helper;
using QYmall.Core.DBFactory.Database;
using QYmall.Core.IServices;
using QYmall.Core.Model.Models;
using QYmall.Core.Model.ViewModels;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace QYmall.Core.Services
{
    public class ShopGoodsFavoriteService : BaseService, IShopGoodsFavoriteService
    {
        private readonly IUserService _userService;
        private readonly IMapper _mapper;

        public ShopGoodsFavoriteService(IDbContextFactory contentFactory, IUserService userService, IMapper mapper) : base(contentFactory)
        {
            _userService = userService;
            _mapper = mapper;
        }

        /// <summary>
        /// 查询一条记录
        /// </summary>
        public async Task<ShopGoodsFavorite?> QueryAsync(Expression<Func<ShopGoodsFavorite, bool>> funcWhere, WriteRoRead writeAndRead = WriteRoRead.Read)
        {
            _context = _contextFactory.CreateContext(writeAndRead);//连接数据库

            var result = await _context.Set<ShopGoodsFavorite>()
                .Include(x => x.ShopGoods)
                .FirstOrDefaultAsync(funcWhere);
            return result;
        }

        /// <summary>
        /// 查询前几条数据
        /// </summary>
        public async Task<IEnumerable<ShopGoodsFavorite>> QueryListAsync(int top, Expression<Func<ShopGoodsFavorite, bool>> funcWhere, 
            string orderBy, WriteRoRead writeAndRead = WriteRoRead.Read)
        {
            _context = _contextFactory.CreateContext(writeAndRead);//连接数据库

            var result = _context.Set<ShopGoodsFavorite>()
                .Include(x => x.ShopGoods)
                .Where(funcWhere);
            result = result.OrderByBatch(orderBy);//调用Linq扩展类排序

            if (top > 0) result = result.Take(top);
            return await result.ToListAsync();
        }

        /// <summary>
        /// 查询分页列表
        /// </summary>
        public async Task<PaginationList<ShopGoodsFavorite>> QueryPageAsync(int pageSize, int pageIndex, Expression<Func<ShopGoodsFavorite, bool>> funcWhere,
            string orderBy, WriteRoRead writeAndRead = WriteRoRead.Read)
        {
            _context = _contextFactory.CreateContext(writeAndRead);//连接数据库
            var result = _context.Set<ShopGoodsFavorite>()
                .Include(x => x.ShopGoods)
                .Where(funcWhere).OrderByBatch(orderBy);//调用Linq扩展类排序
            return await PaginationList<ShopGoodsFavorite>.CreateAsync(pageIndex, pageSize, result);
        }

        /// <summary>
        /// 添加一条记录
        /// </summary>
        public async Task<ShopGoodsFavoriteDto> AddAsync(ShopGoodsFavoriteEditDto modelDto, WriteRoRead writeAndRead = WriteRoRead.Write)
        {
            _context = _contextFactory.CreateContext(writeAndRead);//连接数据库

            //获取登录用户ID
            var userId = await _userService.GetUserIdAsync();
            if (userId == 0)
            {
                throw new ResponseException("用户尚未登录");
            }
            //获取收藏记录，检查是否重复增加
            var favoriteModel = await _context.Set<ShopGoodsFavorite>().FirstOrDefaultAsync(x => x.UserId == userId && x.GoodsId == modelDto.GoodsId);
            if (favoriteModel != null)
            {
                return _mapper.Map<ShopGoodsFavoriteDto>(favoriteModel);
            }
            //获取商品信息
            var goodsModel = await _context.Set<ShopGoods>().FirstOrDefaultAsync(x => x.Id == modelDto.GoodsId);
            if (goodsModel == null)
            {
                throw new ResponseException($"商品{modelDto.GoodsId}不存在或已删除");
            }
            //映射成实体
            var model = _mapper.Map<ShopGoodsFavorite>(modelDto);
            model.UserId = userId;
            model.Title = goodsModel.Title;
            model.ImgUrl = goodsModel.ImgUrl;
            //商品收藏加一，设置只修改一项
            goodsModel.FavoriteCount ++;
            /*var entry = _context.Entry<ShopGoods>(goodsModel);
            entry.State = EntityState.Unchanged;
            entry.Property(x => x.FavoriteCount).IsModified = true;*/
            //保存
            _context.Set<ShopGoods>().Update(goodsModel);
            await _context.Set<ShopGoodsFavorite>().AddAsync(model);
            var result = await this.SaveAsync();
            if (!result)
            {
                throw new ResponseException("添加收藏发生错误，请联系管理员");
            }
            //映射成DTO
            return _mapper.Map<ShopGoodsFavoriteDto>(model);
        }

        /// <summary>
        /// 根据条件删除记录
        /// </summary>
        public async Task<bool> DeleteAsync(Expression<Func<ShopGoodsFavorite, bool>> funcWhere, WriteRoRead writeAndRead = WriteRoRead.Write)
        {
            _context = _contextFactory.CreateContext(writeAndRead); //连接数据库

            var list = await _context.Set<ShopGoodsFavorite>().Where(funcWhere).ToListAsync();
            if (list == null)
            {
                return false;
            }
            //循环查找商品
            List<ShopGoods> goodsList = new();
            foreach (var item in list)
            {
                var goodsModel = goodsList.FirstOrDefault(x => x.Id == item.GoodsId);
                if(goodsModel != null && goodsModel.FavoriteCount > 0)
                {
                    goodsModel.FavoriteCount--;
                }
                else
                {
                    goodsModel = await _context.Set<ShopGoods>().FirstOrDefaultAsync(x => x.Id == item.GoodsId);
                    if (goodsModel != null && goodsModel.FavoriteCount > 0)
                    {
                        goodsModel.FavoriteCount--;
                        goodsList.Add(goodsModel);
                    }
                }
            }
            _context.Set<ShopGoodsFavorite>().RemoveRange(list);
            _context.Set<ShopGoods>().UpdateRange(goodsList);
            return await this.SaveAsync();
        }
    }
}
